<?php

namespace app\shop\controller;

use app\common\service\Status;
use app\shop\model\ShopSeckillGood;
use buildView\Actions;
use buildView\Button;
use think\Controller;
use buildView\Detail;
use buildView\Form;
use buildView\Grid;
use app\shop\model\ShopSeckillActivity;

class SeckillActivity extends Controller
{
    /**
     * 列表
     * @auth true
     * @menu true
     * @return string
     */
    public function index()
    {
        $grid = new Grid(new ShopSeckillActivity);
        $grid->name('活动名称');
        $grid->user_shop_num('每人每件商品限购数量');
        $grid->status('活动状态')->using(Status::ACTIVITYSTATUS())->badge();
        $grid->start_time('开始时间');
        $grid->end_time('结束时间');
        $grid->setFromOpen();
        $grid->filter(function ($filter) {
            $filter->like('name', '活动名称');
            $filter->eq('status', '活动状态')->select(Status::ACTIVITYSTATUS());
        });
        $grid->actions(function (Actions $action,$data) {
            $action->hideDetail();
            $button = new Button('商品列表','warm');
            $button->href(url('shop').'?back=1&activity_id='.$data['id']);
            $action->prepend($button);
        });
        $grid->hideExportButton();
        return $grid->view();
    }

    /**
     * 秒杀商品列表
     * @auth true
     * @menu true
     * @Author: rocky
     * 2019/12/10 17:35
     */
    public function shop(){
        $activity_id = $this->request->get('activity_id');
        $grid = new Grid(new ShopSeckillGood());
        $grid->model()->where('activity_id',$activity_id)->with(['good'=>function($q){
            $q->withSum('specs', 'stock')->withSum(['specs' => function ($q) {
                return 'sale_num';
            }], 'sale');
        }]);
        $grid->setTitle('秒杀活动商品');
        $stock_warning = sysconf('stock_warning');
        $grid->logo('商品图片')->width(100)->image(5, 80, 80);
        $grid->column('info', '商品信息')->display(function ($val, $data) {
            $data = $data['good'];
            $html = "商品编号：{$data['id']}<br>商品名称：{$data['title']}";
            return $html;
        })->width(200)->align('left');

        $grid->good()->specs('<div class="layui-row" style="line-height:28px">
                    <div class="layui-col-xs6 text-left layui-elip">商品规格</div>
                    <div class="layui-col-xs3 text-center layui-elip">秒杀价</div>
                    <div class="layui-col-xs3 text-center layui-elip">库存 / 销量 / 剩余库存</div>
                </div>')
            ->display(function ($specs, $data) use ($stock_warning) {
                $html = '<div class="layui-row" style="line-height:23px">
                        <div class="layui-col-xs6 text-left layui-elip font-s10">--</div>
                        <div class="layui-col-xs3 text-center layui-elip color-blue font-s10">--</div>
                        <div class="layui-col-xs3 text-center layui-elip color-blue font-s10">--</div>
                    </div>';
                if ($specs->isEmpty()) {
                    return $html;
                } else {
                    $html = '<div style="overflow:auto;max-height:68px;padding:5px 0">';
                }
                foreach ($specs as $spec) {
                    $stock = $spec['stock'] - $spec['sale'];
                    if ($stock <= $stock_warning) {
                        $stock = '<span class="color-red">' . $stock . '</span>';
                    }

                    $html .= ' <div class="layui-row" style="line-height:23px">
                        <div class="layui-col-xs6 text-left layui-elip font-s10">' . str_replace(['::', ';;'], [':', ';'], $spec['spec_name']) . '</div>
                        <div class="layui-col-xs3 text-center layui-elip color-blue font-s10">' . $spec['seckill_price']. '</div>
                        <div class="layui-col-xs3 text-center layui-elip color-blue font-s10">' . $spec['stock'] . ' / ' . $spec['sale'] . ' / ' . $stock . '</div>
                    </div>';
                }
                $html .= '</div>';
                return $html;
            })->minWidth(550)->align('left');

        $grid->column('sale_num', '库存统计')->display(function ($val, $data) use ($stock_warning) {
            $data = $data['good'];
            $stock = $data['specs_sum'] ? $data['specs_sum'] : 0;
            $sale = $data['sale_num'] ? $data['sale_num'] : 0;
            $stock_num = $stock - $sale;
            if ($stock_num <= $stock_warning) {
                $stock_num = '<span class="color-red">剩余库存：' . $stock_num . '</span>';
            } else {
                $stock_num = '<span>剩余库存：' . $stock_num . '</span>';
            }
            return '库存：' . $stock . '<br>' . $stock_num . '<br>销量：<span class="layui-badge layui-bg-green">' . $sale . '</span>';
        })->width(150)->align('left');
        $grid->good()->price('价格')->display(function ($val, $data) {
            $data = $data['good'];
            return '价格：￥' . $data['price'] . '<br>运费：￥' . $data['price_express'];
        })->width(150)->align('left');
        $grid->hideExportButton();
        $grid->hideAddButton();
        $button = new Button('选择商品');
        $button->href(url('goods/index').'?activity_id='.$activity_id,'iframe');
        $grid->addTools($button);
        $grid->actions(function ($action,$data){
           $action->hideDetail();
           $action->hideEdit();
            $button = new Button('编辑','','sm','layui-icon-edit');
            $button->href(url('goods/form').'?back=1&id='.$data['good_id']);
            $action->prepend($button);
        });
        return $grid->view();
    }

    /**
     *添加秒杀商品
     * @auth true
     * @menu true
     * @Author: rocky
     * 2019/12/10 18:18
     * @throws \Exception
     */
    public function addGood(){
        $good_ids = $this->request->put('select_ids');
        $activity_id = $this->request->put('value');
        $good_idsArr = explode(',',$good_ids);
        $data = [];
        foreach ($good_idsArr as $val){
            $data[] = [
              'good_id'=>$val,
              'activity_id'=>$activity_id
            ];
        }
        (new ShopSeckillGood())->saveAll($data);
        $this->success('添加成功','');
    }
    /**
     * 添加/编辑
     * @auth true
     * @menu true
     * @return string
     */
    public function form()
    {
        $form = new Form(new ShopSeckillActivity);
        $form->text('name', '活动名称')->required();
        $form->number('user_shop_num', '每人每件商品限购数量')->layui('inline')->default(1)->required();
        $form->datetime('start_time', '开始时间')->required();
        $form->datetime('end_time', '结束时间')->required();
        $form->saving(function ($post) {
            if ($post['end_time'] < $post['start_time']) {
                $this->error('结束时间不能早于开始时间', '');
            }
            $db = ShopSeckillActivity::where('end_time', '>=', $post['start_time'])
                ->where('start_time', '<=', $post['end_time']);
            if (!empty($post['id'])) {
                $db->where('id', '<>', $post['id']);
            }
            $count = $db->count();
            if ($count > 0) {
                $this->error('时间选择错误,存在相同时间段', '');
            }
            $time = date('Y-m-d H:i:s');
            $start_time = $post['start_time'];
            $end_time = $post['end_time'];
            if ($start_time < $time && $end_time >= $time) {
                $post['status'] = 2;
            } elseif ($start_time > $time) {
                $post['status'] = 1;
            } elseif ($end_time < $time) {
                $post['status'] = 3;
            }

            return $post;
        });
        return $form->view();
    }
}
